/**
 * SQL Section
 * This class will establish connection to database.
 * Class is extended by Query.class which contains instructions to close connection and to send string query.
 * Information about connection stages can be retrieved from debug variable.
 * @author Master
 */
import java.sql.*;

public class SqlSetConnection {

    String driver;
    String server;
    String props;
    // Here we'll store all debug information
    public String debug = "";

    /*
     * Constructor
     */
    public SqlSetConnection(String driver, String server, String props) {
        this.driver = driver;
        this.server = server;
        this.props = props;
    }

    /*
     * Debug method for debug property
     */
    public String debug() {
        return this.debug;
    }
    
    /*
     * Make string representation of the current time for debugging
     */
    private static String currentTime() {
        // Format the current time.
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
                "yyyy-MM-dd 'at' hh:mm:ss a zzz ':' ");
        return formatter.format(new java.util.Date());
    }

    /*
     * Append debug info tu debug variable Function is visible for all child
     * classes
     */
    protected void debug(String s) {
        this.debug += currentTime() + s + "\n";
    }

    /*
     * Main function. Tries and establishes connection to database with given
     * parameters, Logs major information to debug variable
     * 
     * @return Connection
     */
    public Connection connect() throws Exception {
        Connection connection = null;
        try {
            Class.forName(this.driver).newInstance();

            debug("DriverManager.getConnection(" + this.server + this.props);
            while (connection == null) {
                connection = DriverManager.getConnection(this.server
                        + this.props);
            }
            debug("Connection established.");
        } catch (ClassNotFoundException ex) {
            debug("Database driver not found " + this.driver);
            throw (ex);
        } catch (SQLException ex) {
            SQLException ex1 = ex;
            while (ex != null) {
                // there may be a pile of errors
                debug("SQL State =  " + ex.getSQLState());
                // 08s01 = Communication link failure
                // 28000 = Invalid authorization specification
                debug(ex.getMessage() + "Cannot connect to the database at "
                        + this.server);
                ex = ex.getNextException();
            }
            throw (ex1);
        } catch (Exception ex) {
            // catch anything else out there
            throw (ex);
        }
        return connection;
    }
}
